package com.hxut.utils;

import java.sql.*;

import static java.sql.DriverManager.getConnection;

public class JdbcUtils {

    //获取数据库
    public static Connection getConnect() throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/cakesdb?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT";
        String username = "root";
        String password = "123456";
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取链接
        Connection connection = getConnection(url, username, password);
        return connection;
    }

    //关闭数据库，释放资源
    public static void release(Statement statement,Connection connection){
        //关闭Statement 对象，释放Statement对象资源
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            statement =null;
        }
        //Connection 对象，Connection对象资源
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //关闭数据库，释放资源
    public static void release(ResultSet resultSet, Statement statement, Connection connection){
        //关闭ResultSet 对象
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            resultSet=null;
        }
        release(statement,connection);
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        System.out.println(getConnect());
    }
}

